package com.chagee.store.operation.server.facade;

import com.chagee.store.operation.api.request.WorkOrderRequest;
import com.chagee.store.operation.common.exception.BizErrorCode;
import com.chagee.store.operation.server.model.lock.ExportLock;
import com.chagee.store.operation.server.model.vo.EvaluateInfoResponse;
import com.chagee.store.operation.server.model.param.QueryEvaluateListParam;
import com.chagee.store.operation.server.redis.service.RedisLockService;
import com.chagee.store.operation.server.service.StoreOrderEvaluateService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;

/**
 * @Author : hk
 * @Date : 2024/4/29
 */

@Slf4j
@Service
@RequiredArgsConstructor
public class StoreOrderEvaluateFacade {

	@Resource
	private StoreOrderEvaluateService storeOrderEvaluateService;

	@Resource
	private RedisLockService redisLockService;

	public List<EvaluateInfoResponse> list(QueryEvaluateListParam param) {
		List<EvaluateInfoResponse> result = storeOrderEvaluateService.list(param);
		return result;
	}

	public void evaluateExport(WorkOrderRequest param, HttpServletRequest request, HttpServletResponse response, ModelMap map) {
		BladeUser user = AuthUtil.getUser();
		String userId = Objects.nonNull(user) ? String.valueOf(user.getUserId()) : StringUtils.EMPTY;
		ExportLock lock = null;
		if (Objects.nonNull(userId)) {
			lock = new ExportLock(userId);
		}
		try {
			redisLockService.lockElseThrowError(lock, BizErrorCode.PLEASE_WAIT.getErrorMsg());
			storeOrderEvaluateService.evaluateExport(param,request, response,map);
		} finally {
			redisLockService.unLock(lock);
		}

	}
}
